<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.datatype"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入数据类别"
      />
      <el-input
        v-model="listQuery.datadesc"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入数据描述"
      />

      <el-button v-permission="['admin:dict:list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['admin:dict:create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" prop="id" sortable />
      <el-table-column align="center" label="上级ID" prop="pid" sortable />

      <el-table-column align="center" label="数据类别" prop="datatype" />
      <el-table-column align="center" label="数据名称" prop="datacode" />
      <el-table-column align="center" label="数据值" prop="datavalue" />
      <el-table-column align="center" label="数据描述" prop="datadesc" />
      <el-table-column align="center" label="顺序" prop="sortno" />

      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['admin:dict:update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['admin:dict:delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          <!--<el-button v-permission="['']" type="primary" size="mini" @click="handlePermission(scope.row)">扩展</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >

        <el-form-item label="上级ID" prop="pid">
          <el-input v-model="dataForm.pid" />
        </el-form-item>

        <el-form-item label="数据类别" prop="datatype">
          <el-input v-model="dataForm.datatype" />
        </el-form-item>

        <el-form-item label="数据名称" prop="datacode">
          <el-input v-model="dataForm.datacode" />
        </el-form-item>

        <el-form-item label="数据值" prop="datavalue">
          <el-input v-model="dataForm.datavalue" />
        </el-form-item>

        <el-form-item label="数据描述" prop="datadesc">
          <el-input v-model="dataForm.datadesc" />
        </el-form-item>
        <el-form-item label="顺序" prop="sortno">
          <el-input v-model="dataForm.sortno" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDict,
  createDict,
  updateDict,
  deleteDict
} from '@/api/dict'
import { formatDateAndTime } from '@/filters'
import Pagination from '@/components/Pagination'

export default {
  name: 'Dict',
  components: { Pagination },
  filters: {
    formatGmt(time) {
      if (time == null || time === '') {
        return '无'
      }
      return formatDateAndTime(time)
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        sort: 'gmt_update',
        order: 'desc'
      },
      dataForm: {
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        datatype: [
          { required: true, message: '数据类别不能为空', trigger: 'blur' }
        ],
        datacode: [{ required: true, message: '数据名不能为空', trigger: 'blur' }],
        datavalue: [{ required: true, message: '数据值不能为空', trigger: 'blur' }],
        datadesc: [{ required: true, message: '数据描述不能为空', trigger: 'blur' }]
      },

      dialogFormVisible: false,
      dialogStatus: ''

    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listDict(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        desc: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      console.log(this.dataForm)
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createDict(this.dataForm)
            .then(response => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加系统字典表成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateDict(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新系统字典表成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该系统字典表---' + row.id + '---, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDict(row.id).then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除系统字典表成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        }).catch(response => {
          this.$notify.error({ title: '失败', message: response.data.errmsg })
        })
      })
        .catch(() => {
          return false
        })
    }

  }
}
</script>
